<template>
  <el-dialog :title="title"
             :visible.sync="visible"
             v-loading="loading"
             :before-close="modalClose"
             :close-on-click-modal="false"
             :close-on-press-escape="false"
             width="50%"
             append-to-body>

    <el-form ref="formRef"
             :model="formModel"
             :rules="formRules"
             label-width="120px">
      <!-- 化学药 -西药 -->
      <el-form-item label="化学药：">
        <el-select v-model="drugId1"
                   placeholder="请选择化学药"
                   multiple
                   filterable
                   remote
                   reserve-keyword
                   clearable
                   :remote-method="(query) => {remoteMethod(query, 2)}"
                   :loading="loading1"
                   class="w-200"
                   @change="val=>handleSelect(val, 2)">
          <el-option v-for="item in options1"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id">
          </el-option>
        </el-select>
        <el-button type="primary"
                   @click="handleAddDetect(drugId1, 2, '请选择化学药')">新 增</el-button>
      </el-form-item>
      <el-form-item label="已选化学药：">
        <el-table :data="tableData1"
                  style="width: 100%"
                  border>
          <el-table-column prop="drugName"
                           label="药品名称">
          </el-table-column>
          <el-table-column prop="factoryName"
                           label="厂家">
          </el-table-column>
          <el-table-column prop="specifications"
                           label="规格">
          </el-table-column>
          <el-table-column prop="option"
                           label="操作">
            <template slot-scope="scope">
              <el-button type="danger"
                         @click="removeTable(tableData1, scope.$index)">删除</el-button>
            </template>
          </el-table-column>

        </el-table>
      </el-form-item>
      <!-- 中成药 -->
      <el-form-item label="中成药：">
        <el-select v-model="drugId2"
                   placeholder="请选择中成药"
                   multiple
                   filterable
                   remote
                   reserve-keyword
                   :remote-method="(query) => {remoteMethod(query, 3)}"
                   :loading="loading2"
                   class="w-200"
                   @change="val=>handleSelect(val, 3)">
          <el-option v-for="item in options2"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id">
          </el-option>
        </el-select>
        <el-button type="primary"
                   @click="handleAddDetect(drugId2, 3, '请选择中成药')">新 增</el-button>
      </el-form-item>
      <el-form-item label="已选中成药：">
        <el-table :data="tableData2"
                  style="width: 100%"
                  border>
          <el-table-column prop="drugName"
                           label="药品名称">
          </el-table-column>
          <el-table-column prop="factoryName"
                           label="厂家">
          </el-table-column>
          <el-table-column prop="specifications"
                           label="规格">
          </el-table-column>
          <el-table-column prop="option"
                           label="操作">
            <template slot-scope="scope">
              <el-button type="danger"
                         @click="removeTable(tableData2, scope.$index)">删除</el-button>
            </template>
          </el-table-column>

        </el-table>
      </el-form-item>
      <!-- 保健品 -->
      <el-form-item label="保健品：">
        <el-select v-model="drugId3"
                   placeholder="请选择保健品"
                   multiple
                   filterable
                   remote
                   reserve-keyword
                   :remote-method="(query) => {remoteMethod(query, 4)}"
                   :loading="loading3"
                   class="w-200"
                   @change="val=>handleSelect(val, 4)">
          <el-option v-for="item in options3"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id">
          </el-option>
        </el-select>
        <el-button type="primary"
                   @click="handleAddDetect(drugId3, 4, '保健品')">新 增</el-button>
      </el-form-item>
      <el-form-item label="已选保健品：">
        <el-table :data="tableData3"
                  style="width: 100%"
                  border
                  class="mt-20">
          <el-table-column prop="drugName"
                           label="药品名称">
          </el-table-column>
          <el-table-column prop="factoryName"
                           label="厂家">
          </el-table-column>
          <el-table-column prop="specifications"
                           label="规格">
          </el-table-column>
          <el-table-column prop="option"
                           label="操作">
            <template slot-scope="scope">
              <el-button type="danger"
                         @click="removeTable(tableData3, scope.$index)">删除</el-button>
            </template>
          </el-table-column>

        </el-table>
      </el-form-item>
      <!-- 器械 -->
      <el-form-item label="器械：">
        <el-select v-model="drugId4"
                   placeholder="请选择器械"
                   multiple
                   filterable
                   remote
                   reserve-keyword
                   :remote-method="(query) => {remoteMethod(query, 5)}"
                   :loading="loading4"
                   class="w-200"
                   @change="val=>handleSelect(val, 5)">
          <el-option v-for="item in options4"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id">
          </el-option>
        </el-select>
        <el-button type="primary"
                   @click="handleAddDetect(drugId4, 5, '请选择器械')">新 增</el-button>
      </el-form-item>
      <el-form-item label="已选器械：">
        <el-table :data="tableData4"
                  style="width: 100%"
                  border
                  class="mt-20">
          <el-table-column prop="drugName"
                           label="药品名称">
          </el-table-column>
          <el-table-column prop="factoryName"
                           label="厂家">
          </el-table-column>
          <el-table-column prop="specifications"
                           label="规格">
          </el-table-column>
          <el-table-column prop="option"
                           label="操作">
            <template slot-scope="scope">
              <el-button type="danger"
                         @click="removeTable(tableData4, scope.$index)">删除</el-button>
            </template>
          </el-table-column>

        </el-table>
      </el-form-item>

      <el-form-item label="销售话术：">
        <el-input type="textarea"
                  v-model="formModel.recommendSalesScript"
                  placeholder="请输入销售话术"></el-input>
      </el-form-item>
    </el-form>
    <p align="center">
      <el-button type="info"
                 @click="modalClose">取 消</el-button>
      <el-button type="primary"
                 @click="submitForm">新 增</el-button>
    </p>
  </el-dialog>
</template>
<script>
  export default {
    name: 'medicineDialog', // 联合荐药
    props: {
      medicineDataObj: {
        type: Object,
        default: {}
      },
      visible: {
        type: Boolean,
        default: false
      },
    },
    data () {
      return {
        title: '新增联合荐药',
        loading: false,
        loading1: false,
        loading2: false,
        loading3: false,
        loading4: false,
        dataList1: [],
        dataList2: [],
        dataList3: [],
        dataList4: [],
        options1: [],
        options2: [],
        options3: [],
        options4: [],
        imageUploadUrl: this.api.appUpgradeUpload.url,
        formModel: {
          recommendSalesScript: '', // 销售话术
        },
        formRules: {
          name: [{ required: false, message: '请输入器械名称', trigger: 'blur' }]
        },
        tableData1: [], // 已选化学药
        tableData2: [], // 已选中成药
        tableData3: [], // 已选保健品
        tableData4: [], // 已选中成药
        drugId1: [],
        drugId2: [],
        drugId3: [],
        drugId4: [],
        typeList: [
          { drugType: 2, drugName: "化学药" },
          { drugType: 3, drugName: "中成药" },
          { drugType: 4, drugName: "保健品" },
          { drugType: 5, drugName: "器械" }
        ]
      }
    },
    methods: {
      modalClose () {
        this.$emit('update:visible', false); // 直接修改父组件的属性
      },
      submitForm () {
        this.$refs.formRef.validate((valid) => {
          if (valid) {
            this.$set(this.formModel, 'tableData', [...this.tableData1, ...this.tableData2, ...this.tableData3, ...this.tableData4]);
            this.$emit('childMedicineData', this.formModel);
            this.modalClose();
          }
        })
      },

      removeTable (table, index, option) {
        table.splice(index, 1);
      },
      // 搜索联合荐药
      remoteMethod (query, type) {
        if (query !== '') {
          let _this = this;
          let loadingKey = 'loading' + (type - 1);
          _this[loadingKey] = true; // 锁住
          this.post(this.api.promote.getRecommendDrug, {
            name: query,
            typeList: [type]
          }).then(res => {
            if (res.data.code === '200') {
              let dataListKey = 'dataList' + (type - 1);
              _this[loadingKey] = false;
              _this[dataListKey] = res.data.object;
            }
          })

          /**
           * 搜索内容渲染到下拉框
           * 从 this.dataList1 把数据赋值到 this.options1
           * 只有这样才能起作用
           */
          setTimeout(() => {
            let loadingKey = 'loading' + (type - 1);
            let dataListKey = 'dataList' + (type - 1);
            let optionsKey = 'options' + (type - 1);
            _this[loadingKey] = false;
            _this[optionsKey] = _this[dataListKey].filter(item => item.name.indexOf(query) > -1);
          }, 200);
        } else {
          let key = 'options' + (type - 1);
          this[key] = [];
        }
      },
      // 远程搜索请求联合荐药列表
      getList (data, selVal) {
        let temp = data.filter(item => selVal.some(ele => ele === item.id))
          .map(({
            factoryName,
            id,
            name,
            standard,
            type
          }) => ({
            drugId: id,
            drugType: type,
            drugName: name,
            factoryName,
            specifications: standard
          }));
        return temp;
      },
      // 增加推推荐检测项
      handleAddDetect (selVal, type, text) {
        if (selVal.length === 0) {
          this.$message.error(text);
          return
        }
        let dataListKey = 'dataList' + (type - 1);
        let tableDataKey = 'tableData' + (type - 1);
        let drugIdKey = 'drugId' + (type - 1);
        try {
          this[tableDataKey].forEach(item => selVal.some(ele => {
            if (item.drugId === ele) {
              this.$message.warning('同类型药品不能重复添加!');
              this[drugIdKey] = [];
              throw new Error('e');
            }
          }))
          let tempKey = this.getList(this[dataListKey], selVal);
          this[tableDataKey] = [...this[tableDataKey], ...tempKey];
        } catch (e) {
          if (e.message !== 'e') { throw e }
        }
      },
      handleSelect (item, type) {
        let key = 'drugId' + (type - 1);
        this[key] = item;
      },

    },
    created () {
      this.$nextTick(_ => {
        this.formModel.recommendSalesScript = this.medicineDataObj.recommendSalesScript;
        const result = this.typeList.map(item => ({
          ...item,
          value: this.medicineDataObj.recommendMedicineRequestDtoList.filter(sItem => item.drugType === sItem.drugType)
        }))
        result.forEach((item, index) => {
          let key = 'tableData' + (index + 1);
          this[key] = item.value;
        })
      })
    }
  }
</script>
<style scoped lang="scss">
</style>